package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.PointsMallGoods;
import org.dromara.system.domain.PointsMallRecords;
import org.dromara.system.domain.SysUserPurse;
import org.dromara.system.domain.bo.CommodityExchangeBo;
import org.dromara.system.domain.bo.PointsMallRecordsBo;
import org.dromara.system.domain.bo.SysUserPurseBo;
import org.dromara.system.domain.vo.PointsMallRecordsVo;
import org.dromara.system.enums.MachineConstant;
import org.dromara.system.enums.SysUserPointsRecordsEnum;
import org.dromara.system.mapper.PointsMallRecordsMapper;
import org.dromara.system.service.IPointsMallGoodsService;
import org.dromara.system.service.IPointsMallRecordsService;
import org.dromara.system.service.ISysUserPointsRecordsService;
import org.dromara.system.service.ISysUserPurseService;
import org.dromara.system.service.impl.permission.PermissionBaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 积分商城订单Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-24
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PointsMallRecordsServiceImpl extends ServiceImpl<PointsMallRecordsMapper, PointsMallRecords> implements IPointsMallRecordsService {

    public static final String PREFIX = "MALL-";
    private final IPointsMallGoodsService pointsMallGoodsService;
    private final ISysUserPurseService sysUserPurseService;
    private final ISysUserPointsRecordsService sysUserPointsRecordsService;
    private final PermissionBaseService permissionBaseService;

    public static synchronized String getOrderNo(int digit) {
        StringBuilder resultBuffer = new StringBuilder();
        resultBuffer.append(PREFIX)
            .append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        Random random = new Random();
        for (int i = 0; i < digit; i++) {
            resultBuffer.append(random.nextInt(10));
        }
        return resultBuffer.toString();
    }

    /**
     * 查询积分商城订单
     *
     * @param id 主键
     * @return 积分商城订单
     */
    @Override
    public PointsMallRecordsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询积分商城订单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 积分商城订单分页列表
     */
    @Override
    public TableDataInfo<PointsMallRecordsVo> queryPageList(PointsMallRecordsBo bo, PageQuery pageQuery) {
        permissionBaseService.assignPermission(bo);
        IPage<PointsMallRecordsVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<PointsMallRecordsVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    @Override
    public TableDataInfo<PointsMallRecordsVo> listReception(PointsMallRecordsBo bo, PageQuery pageQuery) {
        permissionBaseService.aloneAssignPermission(bo);
        IPage<PointsMallRecordsVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<PointsMallRecordsVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    /**
     * 查询符合条件的积分商城订单列表
     *
     * @param bo 查询条件
     * @return 积分商城订单列表
     */
    @Override
    public List<PointsMallRecordsVo> queryList(PointsMallRecordsBo bo) {
        LambdaQueryWrapper<PointsMallRecords> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PointsMallRecords> buildQueryWrapper(PointsMallRecordsBo bo) {
        LambdaQueryWrapper<PointsMallRecords> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(PointsMallRecords::getId);
        lqw.eq(bo.getUserId() != null, PointsMallRecords::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getNo()), PointsMallRecords::getNo, bo.getNo());
        lqw.eq(bo.getStatus() != null, PointsMallRecords::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getGoodsTitle()), PointsMallRecords::getGoodsTitle, bo.getGoodsTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getGoodsImage()), PointsMallRecords::getGoodsImage, bo.getGoodsImage());
        lqw.eq(bo.getGoodPoints() != null, PointsMallRecords::getGoodPoints, bo.getGoodPoints());
        lqw.eq(StringUtils.isNotBlank(bo.getExchangeAccount()), PointsMallRecords::getExchangeAccount, bo.getExchangeAccount());
        return lqw;
    }

    /**
     * 新增积分商城订单
     *
     * @param bo 积分商城订单
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(PointsMallRecordsBo bo) {
        PointsMallRecords add = MapstructUtils.convert(bo, PointsMallRecords.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改积分商城订单
     *
     * @param bo 积分商城订单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(PointsMallRecordsBo bo) {
        PointsMallRecords update = MapstructUtils.convert(bo, PointsMallRecords.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PointsMallRecords entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除积分商城订单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean commodityExchange(CommodityExchangeBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        PointsMallGoods goods = pointsMallGoodsService.getById(bo.getGoodsId());
        Integer inventory = goods.getInventory();
        BusinessException.isTrue(inventory <= 0, "库存不足！");
        //查询余额
        SysUserPurse sysUserPurse = sysUserPurseService.lambdaQuery().eq(SysUserPurse::getUserId, bo.getUserId()).one();
        BigDecimal points = sysUserPurse.getPoints();
        BusinessException.isTrue(NumberUtil.isLess(points, goods.getPoints()), "积分余额不足！");
        //增加兑换记录
        PointsMallRecordsBo build = PointsMallRecordsBo.builder()
            .userId(bo.getUserId())
            .no(getOrderNo(10))
            .status(MachineConstant.NUMBER.ZERO)
            .goodsTitle(goods.getTitle())
            .goodsImage(goods.getImage())
            .goodPoints(NumberUtil.mul(goods.getPoints(), MachineConstant.NUMBER.ONE_NEGATIVE))
            .exchangeAccount(bo.getExchangeAccount())
            .build();
        insertByBo(build);
        //扣除用户钱包
        SysUserPurseBo sysUserPurseBo = SysUserPurseBo.builder()
            .userId(bo.getUserId())
            .type(SysUserPointsRecordsEnum.EXCHANGE_POINTS.getCode())
            .points(NumberUtil.mul(goods.getPoints(), MachineConstant.NUMBER.ONE_NEGATIVE))
            .build();
        sysUserPointsRecordsService.updateUserPoints(CollUtil.newArrayList(sysUserPurseBo));
        //修改库存
        pointsMallGoodsService.lambdaUpdate()
            .set(PointsMallGoods::getInventory, goods.getInventory() - 1)
            .eq(PointsMallGoods::getId, goods.getId())
            .update();
        return Boolean.TRUE;
    }


}
